/**
 * HTTP
 * @file HTTP请求
 * @author 李苗苗 <maoer99@139.com>
 */

import axios from 'axios'
// import qs from 'qs'
import { LoadingBar, Message } from 'element-ui'
import router from '@/router'

axios.defaults.withCredentials = true

// 请求拦截器
axios.interceptors.request.use(
    config => {
        let token = window.localStorage.getItem('token')
        if (router.history.current.path === '/taskHall') {} else if (router.history.current.path === '/taskDetaile') {} else if (router.history.current.path === '/serviceAgree') {} else {
            if (token == null) {
                router.replace({
                    path: '/'
                })
            }
        }
        return config
    },
    function(error) {
        // Do something with request error
        return Promise.reject(error)
    }
)

let host = '' // 192.168.96.9 演示地址
let host1 = ''
let host2 = ''
let host3 = ''
let testhost = ''
let globalwss = ''
let globalfilewss = ''
let wxredirect = '' //微信和绑定支付宝成功后的回调地址
let payappid = '' //绑定支付宝的appid
let downloadZip = '' //图纸托管程序下载地址
if (process.env.NODE_ENV === 'production') {
    // 生产环境（正式）
    host = 'https://www.xnsjy.cn:8083'
    host1 = 'https://www.xnsjy.cn:8089'
    host2 = 'https://www.xnsjy.cn:6064'
    host3 = 'https://www.xnsjy.cn:8087'
    globalwss = 'www.xnsjy.cn'
    globalfilewss = 'www.xnsjy.cn:8083'
    wxredirect = 'https://www.xnsjy.cn/xnsjy-vue/dist/#/'
    payappid = '2017101609334098'
    downloadZip = 'https://www.xnsjy.cn/files/cfile.rar'
} else if (process.env.NODE_ENV === 'testing') {
    // 测试环境
    host = 'https://www.xnsjy.cn:8080'
    host1 = 'https://www.xnsjy.cn:8888'
    host2 = 'https://www.xnsjy.cn:6066'
    host3 = 'https://www.xnsjy.cn:8087'
    globalwss = 'www.xnsjy.cn'
    globalfilewss = 'www.xnsjy.cn:8080'
    wxredirect = 'https://www.xnsjy.cn/devdev/xnsjy-vue/dist/#/'
    payappid = '2019080266067712'
    downloadZip = 'https://www.xnsjy.cn/files/cfile-dev.rar'
} else if (process.env.NODE_ENV === 'release') {
    // 预发布环境
    host = 'https://www.xnsjy.cn:8083'
    host1 = 'https://www.xnsjy.cn:8089'
    host2 = 'https://www.xnsjy.cn:6064'
    host3 = 'https://www.xnsjy.cn:8087'
    globalwss = 'www.xnsjy.cn'
    globalfilewss = 'www.xnsjy.cn:8080'
    payappid = '2019080266067712'
    downloadZip = 'https://www.xnsjy.cn/files/cfile-dev.rar'
} else if (process.env.NODE_ENV === 'development') {
    // host = 'https://www.xnsjy.cn:8083' // 开发环境（本地），这里默认NODE_ENV就是development
    // testhost = 'https://192.168.1.239:8083'
    // host1 = 'https://192.168.96.105:8089'
    // host2 = 'https://192.168.96.105:6064'
    // host3 = 'https://192.168.96.105:8087'
    // globalwss = '192.168.96.105'
    host = 'https://www.xnsjy.cn:8080'
    host1 = 'https://www.xnsjy.cn:8888'
    host2 = 'https://www.xnsjy.cn:6066'
    host3 = 'https://www.xnsjy.cn:8087'
    globalwss = 'www.xnsjy.cn'
    globalfilewss = 'www.xnsjy.cn:8080'
    payappid = '2019080266067712'
    wxredirect = 'https://www.xnsjy.cn/devdev/xnsjy-vue/dist/#/'
    downloadZip = 'https://www.xnsjy.cn/files/cfile-dev.rar'
}
/**
 * HTTP
 * @example <caption>基本使用</caption>
 * import HTTP from './service/http.js'
 * const http = new HTTP()
 * http.get(url, params, msg)
 * http.post(url, params, msg)
 * @example <caption>在Vue中使用</caption>
 * this.$http.get(url, params, msg)
 * this.$http.post(url, params, msg)
 */
class HTTP {
    constructor() {
        this.host = host
        this.host1 = host1
        this.host2 = host2
        this.host3 = host3
        this.testhost = testhost
        this.globalwss = globalwss
        this.globalfilewss = globalfilewss
        this.wxredirect = wxredirect
        this.payappid = payappid
        this.downloadZip = downloadZip
        this.timeout = 60000
    }

    /**
     * 抛出异常
     * @param {object} response - 异常信息
     * @param {string} msg - 异常提示文字
     * @private
     */
    _throwError(response, msg) {
        if (response) {
            if (response.status >= 400 && response.status < 500) {
                switch (response.status) {
                    case 401: // 没有登录或者token失效
                        this._errorMsg(response, msg)
                        router.replace({
                            name: 'LoginPage'
                        })
                        break
                    case 403: // 没有权限
                        this._errorMsg(response, msg)
                            // router.replace({name: '403'})
                        break
                    case 404:
                        this._errorMsg(response, msg)
                            // router.push({name: '404'})
                        break
                    default:
                        this._errorMsg(response, msg)
                        break
                }
            } else if (response.status >= 500) {
                this._errorMsg(response, msg)
                    // router.push({name: '500'})
            } else if (response.status === 200) {
                if (response.data.ret === -3) {
                    window.localStorage.clear()
                    Message.error(response.data.errinfo.errmsg)
                    router.replace({
                        path: '/'
                    })
                } else if (response.data.ret === -1) {
                    Message.error(response.data.errinfo.errmsg)
                }
            }
        } else {
            Message.error('请求出现错误')
                // router.push({name: '500'})
        }
    }

    /**
     * 弹出错误信息
     * @param {object} response - 异常信息
     * @param {string} msg - 异常提示文本
     * @private
     */
    _errorMsg(response, msg) {
        if (msg) {
            Message.error(msg)
        } else if (response.data.message) {
            Message.error(response.data.message)
        } else {
            Message.error(response.toString())
        }
    }

    /**
     * GET
     * @param {string} url - 请求的URL
     * @param {object} params - 请求参数
     * @param {string} [msg] - 抛出异常的提示信息
     * @return {Promise}
     */
    get(url, params, msg = '') {
        // LoadingBar.start()
        return new Promise((resolve, reject) => {
            axios
                .get(url, {
                    params,
                    baseURL: this.host,
                    timeout: this.timeout,
                    headers: {
                        token: window.localStorage.getItem('token')
                    }
                })
                .then(response => {
                    this._throwError(response)
                    if (response.status < 400) {
                        // LoadingBar.finish()
                        resolve(response.data)
                    } else {
                        // LoadingBar.error()
                        this._throwError(response, msg)
                        reject(response)
                    }
                })
                .catch(error => {
                    // LoadingBar.error()
                    this._throwError(error, msg)
                    reject(error)
                })
        })
    }

    /**
     * POST
     * @param {string} url - 请求的URL
     * @param {object} params - 请求参数
     * @param {string} [msg] - 抛出异常的提示信息
     * @return {Promise}
     */
    post(url, params, msg = '') {
        // LoadingBar.start()
        return new Promise((resolve, reject) => {
            axios
                .post(url, params, {
                    baseURL: this.host,
                    timeout: this.timeout,
                    headers: {
                        token: window.localStorage.getItem('token')
                    }
                })
                .then(response => {
                    this._throwError(response)
                    if (response.status < 400) {
                        // LoadingBar.finish()
                        resolve(response.data)
                    } else {
                        // LoadingBar.error()
                        this._throwError(response, msg)
                        reject(response)
                    }
                })
                .catch(error => {
                    // LoadingBar.error()
                    this._throwError(error, msg)
                    reject(error)
                })
        })
    }

    testpost(url, params, msg = '') {
            // LoadingBar.start()
            return new Promise((resolve, reject) => {
                axios
                    .post(url, params, {
                        baseURL: this.testhost,
                        timeout: this.timeout,
                        headers: {
                            token: window.localStorage.getItem('token')
                        }
                    })
                    .then(response => {
                        this._throwError(response)
                        if (response.status < 400) {
                            // LoadingBar.finish()
                            resolve(response.data)
                        } else {
                            // LoadingBar.error()
                            this._throwError(response, msg)
                            reject(response)
                        }
                    })
                    .catch(error => {
                        // LoadingBar.error()
                        this._throwError(error, msg)
                        reject(error)
                    })
            })
        }
        // POST1:8089
    post1(url, params, msg = '') {
            // LoadingBar.start()
            return new Promise((resolve, reject) => {
                axios
                    .post(url, params, {
                        baseURL: this.host1,
                        timeout: this.timeout,
                        headers: {
                            token: window.localStorage.getItem('token')
                        }
                    })
                    .then(response => {
                        this._throwError(response)
                        if (response.status < 400) {
                            // LoadingBar.finish()
                            resolve(response.data)
                        } else {
                            // LoadingBar.error()
                            this._throwError(response, msg)
                            reject(response)
                        }
                    })
                    .catch(error => {
                        // LoadingBar.error()
                        this._throwError(error, msg)
                        reject(error)
                    })
            })
        }
        // PUT1:8089
    put1(url, params, msg = '') {
            // LoadingBar.start()
            return new Promise((resolve, reject) => {
                axios
                    .put(url, params, {
                        baseURL: this.host1,
                        timeout: this.timeout,
                        headers: {
                            token: window.localStorage.getItem('token')
                        }
                    })
                    .then(response => {
                        if (response.status < 400) {
                            // LoadingBar.finish()
                            resolve(response.data)
                        } else {
                            // LoadingBar.error()
                            this._throwError(response, msg)
                            reject(response)
                        }
                    })
                    .catch(error => {
                        // LoadingBar.error()
                        this._throwError(error, msg)
                        reject(error)
                    })
            })
        }
        // POST2:6064
    post2(url, params, msg = '') {
            // LoadingBar.start()
            return new Promise((resolve, reject) => {
                axios
                    .post(url, params, {
                        baseURL: this.host2,
                        timeout: 300000,
                        headers: {
                            token: window.localStorage.getItem('uploadToken')
                        }
                    })
                    .then(response => {
                        this._throwError(response)
                        if (response.status < 400) {
                            // LoadingBar.finish()
                            resolve(response.data)
                        } else {
                            // LoadingBar.error()
                            this._throwError(response, msg)
                            reject(response)
                        }
                    })
                    .catch(error => {
                        // LoadingBar.error()
                        this._throwError(error, msg)
                        reject(error)
                    })
            })
        }
        // POST2:8087
    post3(url, params, msg = '') {
            // LoadingBar.start()
            return new Promise((resolve, reject) => {
                axios
                    .post(url, params, {
                        baseURL: 'https://www.xnsjy.cn:8087',
                        timeout: this.timeout,
                        withCredentials: false
                    })
                    .then(response => {
                        this._throwError(response)
                        if (response.status < 400) {
                            // LoadingBar.finish()
                            resolve(response.data)
                        } else {
                            // LoadingBar.error()
                            this._throwError(response, msg)
                            reject(response)
                        }
                    })
                    .catch(error => {
                        // LoadingBar.error()
                        this._throwError(error, msg)
                        reject(error)
                    })
            })
        }
        /**
         * DELETE
         * @param {string} url - 请求的URL
         * @param {object} params - 请求参数
         * @param {string} [msg] - 抛出异常的提示信息
         * @return {Promise}
         */
        // delete:8083
    delete(url, params, msg = '') {
        // LoadingBar.start()
        return new Promise((resolve, reject) => {
            axios
                .delete(url, {
                    params,
                    baseURL: this.host,
                    timeout: this.timeout,
                    headers: {
                        token: window.localStorage.getItem('token')
                    }
                })
                .then(response => {
                    this._throwError(response)
                    if (response.status < 400) {
                        // LoadingBar.finish()
                        resolve(response.data)
                    } else {
                        // LoadingBar.error()
                        this._throwError(response, msg)
                        reject(response)
                    }
                })
                .catch(error => {
                    // LoadingBar.error()
                    this._throwError(error, msg)
                    reject(error)
                })
        })
    }
}

export default HTTP